package com.jdh.config;

import com.alibaba.fastjson2.JSONArray;
import com.jdh.common.Constant;
import com.jdh.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.*;

import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: WebSocketEventListener
 * @Author: jdh
 * @CreateTime: 2022-05-11
 * @Description: 对socket的连接和断连事件进行监听，这样我们才能广播用户进来和出去等操作。
 */
@Slf4j
@Component
public class WebSocketEventListener {

    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations;

    /**
     * 有新用户连接上
     *
     * @param event
     */
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectEvent event) {
//        System.out.println("连接-event => " + event);
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

        String sessionId = event.getMessage().getHeaders().get("simpSessionId").toString();
        User user = JSONArray.parseArray(Objects.requireNonNull(headerAccessor.getNativeHeader("user")).toString(),
                User.class).get(0);
        System.out.println("用户成功连接：" + sessionId + "; 用户:" + user);
        //添加到用户连接列表中
        Constant.connectUserList.put(sessionId, user);
    }

    /**
     * 有客户端断开连接
     *
     * @param event
     */
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
//        System.out.println("断开-event => " + event);
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = event.getSessionId();
        // 在此处执行连接断开时的逻辑处理
        System.out.println("断开连接：" + event.getClass());
        System.out.println("用户断开连接：" + event.getSessionId() + " = " + event);
        //移除在线集合中的用户数据
        Constant.onlineUserList.remove(Constant.connectUserList.get(sessionId).getUuid());
        //移除用户连接列表中当前连接
        Constant.connectUserList.remove(sessionId);
    }

    /***
     * 订阅消息
     * @param event
     */
    @EventListener
    public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
//        log.info("handleWebSocketSubscribeListener - 接收到一个订阅主题的消息:{},用户是:{}", event.getMessage(), event.getUser());
    }

    /***
     * 取消订阅消息
     * @param event
     */
    @EventListener
    public void handleWebSocketUnSubscribeListener(SessionUnsubscribeEvent event) {
//        log.info("handleWebSocketUnSubscribeListener - 接收到一个取消订阅主题的消息:{},用户是:{}", event.getMessage(), event.getUser());
    }
}

